package com.batchengine.service;

import static com.batchengine.Constants.IP_STR;

import java.io.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.StringTokenizer;

/**
 * Created by sunil.incubator@yahoo.com.
 * User: sunil.kalva
 * Date: Jul 11, 2009
 */
public abstract class ServiceImpl implements Service {

    protected String serverName;
    private boolean initialized = false;

    public abstract void init();

    public void init(boolean reinit) {

        if (reinit || !initialized) {
            init();
            initialized = true;
        }
    }

    /**
     * Reads commands from the control port's input stream, processes the command, and sends any output to the control
     * port's output stream.
     *
     * @param in  the input stream
     * @param out the output stream
     * @throws java.io.IOException if an I/O error occurs
     */
    public void service(InputStream in, OutputStream out) throws IOException {

        PrintWriter writer = new PrintWriter(out, true);
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));

        while (true) {
            try {

                writer.println();
                writer.print("> ");
                writer.flush();
                String command = reader.readLine();

                if (command == null) {
                    break;
                }

                boolean exit = handleCommand(command, writer);

                if (exit) {
                    break;
                }
            } catch (IOException ioe) {
                // If we get an IO errro, let's break out of the loop and close the connection.
                throw ioe;
            } catch (Exception e) {
                // If we catch some other exception, let's continue.
                e.printStackTrace(writer);
            }
        }
    }

    private boolean handleCommand(String command, PrintWriter writer) {

        StringTokenizer st = new StringTokenizer(command, " \t");
        if (!st.hasMoreTokens()) {
            return false;
        }

        String commandName = st.nextToken();

        // Prepares arguments for each command.
        Collection<String> list = new ArrayList<String>();
        for (; st.hasMoreTokens();) {
            list.add(st.nextToken());
        }
        String[] args = new String[list.size()];
        list.toArray(args);

        return handleCommand(commandName, args, writer);
    }

    public boolean requiresAuthentication() {
        return false;
    }

    public void setServerName(String serverName) {
        this.serverName = serverName;
    }

    public String getServerName() {
        return serverName;
    }

    public boolean handleCommand(String commandName, String[] args, PrintWriter writer) {

        if (commandName.equalsIgnoreCase("close")) {
            return handleCloseCommand(writer);
        } else if (commandName.equalsIgnoreCase("help") || commandName.equals("?")) {
            return handleHelpCommand(args, writer);
        } else if (commandName.equalsIgnoreCase("health")) {
            return handleHealthCommand(writer);
        } else if (commandName.equalsIgnoreCase("version")) {
            return handleVersionCommand(args, writer);
        } else if (commandName.equalsIgnoreCase("kill")) {
            System.exit(0);
        } else if (commandName.equals("shutdown")) {
            args = new String[]{"server"};
            return handleStopCommand(args, writer);
        } else if (commandName.equals("stop")) {
            return handleStopCommand(args, writer);
        } else
            return handleUnknownCommand(commandName, writer);
        return false;
    }

    private boolean handleHealthCommand(PrintWriter writer) {

        writer.println("starting dbStatus check");
        String fileName = "health.check";
        String dbStatus = getDBStatus();
        writer.println("starting MQStatus check");
        String mqStatus = getMQStatus();

        try {
            PrintWriter pw = new PrintWriter(new FileWriter(fileName));
            pw.println(dbStatus);
            pw.println(mqStatus);
            pw.close();
        } catch (IOException ignored) {
        }
        return false;
    }

    private String getDBStatus() {

        return null;
    }

    private String getMQStatus() {

        return null;
    }

    protected boolean handleUnknownCommand(String commandName, PrintWriter writer) {
        writer.println("Unrecognized command: " + commandName);
        writer.println("Type \"help\" or \"?\" to display usage text.");
        return false;
    }

    protected boolean handleHelpCommand(String[] args, PrintWriter writer) {
        writer.println("Help not yet implemented");
        return false;
    }

    protected boolean handleCloseCommand(PrintWriter writer) {
        writer.println("Closing connection");
        return true;
    }

    //Should be implemented by subclasses for shutting down individual tasks
    //or all tasks gracefully.
    protected boolean handleStopCommand(String[] args, PrintWriter writer) {
        writer.println("Shutting down server");
        System.exit(1);
        return false;
    }

    protected boolean handleVersionCommand(String[] args, PrintWriter writer) {


        try {

            writer.println("in handle: after read props");
            writer.println(serverName + " server version: " + "1.0");
        }
        catch (Exception e) {
            writer.println("Internal error");
        }

        return false;
    }

    protected String getIpAddresses(String[] args) {

        for (String arg : args) {
            if (arg.startsWith(IP_STR)) {
                return arg.substring(IP_STR.length());
            }
        }
        return null;
    }
}
